package com.ruoyi.system.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/system/oss")
public class OssController {

    @Autowired
    RuoYiConfig ruoYiConfig;
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(ruoYiConfig.getEndpoint(), ruoYiConfig.getAccessKeyId(), ruoYiConfig.getAccessKeySecret());
        ObjectMetadata omd = new ObjectMetadata();
        try {
            String status = "";
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//            String imgName = DateUtils.dateTimeNow() + "." + type;
            String imgName = DateUtils.dateTimeNow()+"_"+System.currentTimeMillis()/1000+"_"+file.getOriginalFilename();
            if (ossClient.doesBucketExist(ruoYiConfig.getBucketName())) {
                System.out.println("您已经创建Bucket：" + ruoYiConfig.getBucketName() + "。");
            } else {
                System.out.println("您的Bucket不存在，创建Bucket：" + ruoYiConfig.getBucketName() + "。");

                ossClient.createBucket(ruoYiConfig.getBucketName());
            }
            // 上传图片 部分
            // 使用 ObjectMetadata 对象设置ContentType

            if (type == "mp4" || type.equals("mp4")) {
                omd.setContentType("video/mp4");
//                File file1 = new File(file.getOriginalFilename());
//                // 通过工具类，将文件拷贝到空的文件对象中
//                FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                status = "0";
            }
            if (type == "mp3" || type.equals("mp3")) {
                omd.setContentType("audio/mpeg");
//                File file1 = new File(file.getOriginalFilename());
//                // 通过工具类，将文件拷贝到空的文件对象中
//                FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                status = "0";
            }
            if (type == "pdf" || type.equals("pdf")|| type.equals("PDF")|| type=="PDF") {
                omd.setContentType("application/pdf");
                status = "0";
            }

            if (type == "jpg" || type.equals("jpg")) {
                omd.setContentType("image/jpg");
                status = "0";
            }
            if (type == "png" || type.equals("png")) {
                omd.setContentType("image/jpg");
                status = "0";
            }
            if (StringUtils.isEmpty(status)) {
                return AjaxResult.error("请输入上传正确格式的文件--> .jpg/.png/mp4/mp3/.pdf");
            }
            // 获取文件输出流
//            FileInputStream inputStream = new FileInputStream(imgurl);
//            String newFileName = imgurl.substring(imgurl.lastIndexOf("\\") + 1);
            String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
            // 将文件写入bucket中
            ossClient.putObject(ruoYiConfig.getBucketName(), type+"/"+DateUtils.YYYYMMDD() + "/" + imgName, file.getInputStream(), omd);
            // 关闭输入流
//            inputStream.close();
            // 获取图片链接
            String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type+"/"+DateUtils.YYYYMMDD() + "/" + imgName;
            // 上传文件。
// 设置文件访问权限为公共读。
            ossClient.setObjectAcl(ruoYiConfig.getBucketName(), type+"/"+DateUtils.YYYYMMDD() + "/" + imgName, CannedAccessControlList.PublicRead);
// 关闭OSSClient。
            ossClient.shutdown();

            return AjaxResult.success(url);
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return null;
    }


    @PostMapping("/uploads")
    public AjaxResult uploads(MultipartFile[] files) throws IOException {
            List<String> strings=new ArrayList<>();
            for (MultipartFile file:files) {

                OSS ossClient = new OSSClientBuilder().build(ruoYiConfig.getEndpoint(), ruoYiConfig.getAccessKeyId(), ruoYiConfig.getAccessKeySecret());
                ObjectMetadata omd = new ObjectMetadata();
                String status = "";
                String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//            String imgName = DateUtils.dateTimeNow() + "." + type;
                String imgName = file.getOriginalFilename();
                if (ossClient.doesBucketExist(ruoYiConfig.getBucketName())) {
                    System.out.println("您已经创建Bucket：" + ruoYiConfig.getBucketName() + "。");
                } else {
                    System.out.println("您的Bucket不存在，创建Bucket：" + ruoYiConfig.getBucketName() + "。");

                    ossClient.createBucket(ruoYiConfig.getBucketName());
                }
                // 上传图片 部分
                // 使用 ObjectMetadata 对象设置ContentType

                if (type == "mp4" || type.equals("mp4")) {
                    omd.setContentType("video/mp4");
//                File file1 = new File(file.getOriginalFilename());
//                // 通过工具类，将文件拷贝到空的文件对象中
//                FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                    status = "0";
                }
                if (type == "mp3" || type.equals("mp3")) {
                    omd.setContentType("audio/mpeg");
//                File file1 = new File(file.getOriginalFilename());
//                // 通过工具类，将文件拷贝到空的文件对象中
//                FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                    status = "0";
                }
                if (type == "pdf" || type.equals("pdf") || type.equals("PDF") || type == "PDF") {
                    omd.setContentType("application/pdf");
                    status = "0";
                }

                if (type == "jpg" || type.equals("jpg")|| type.equals("JPG")|| type.equals("jpeg")) {
                    omd.setContentType("image/jpg");
                    status = "0";
                }
                if (type == "png" || type.equals("png")) {
                    omd.setContentType("image/jpg");
                    status = "0";
                }
                if (StringUtils.isEmpty(status)) {
                    return AjaxResult.error("请输入上传正确格式的文件--> .jpg/.png/mp4/mp3/.pdf");
                }
                // 获取文件输出流
//            FileInputStream inputStream = new FileInputStream(imgurl);
//            String newFileName = imgurl.substring(imgurl.lastIndexOf("\\") + 1);
                String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
                // 将文件写入bucket中
                ossClient.putObject(ruoYiConfig.getBucketName(), type + "/20250912/" + imgName, file.getInputStream(), omd);
                // 关闭输入流
//            inputStream.close();
                // 获取图片链接
                String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type + "/20250912/" + imgName + ruoYiConfig.getOssshuiyin();
                // 上传文件。
// 设置文件访问权限为公共读。
                ossClient.setObjectAcl(ruoYiConfig.getBucketName(), type + "/20250912/" + imgName, CannedAccessControlList.PublicRead);
// 关闭OSSClient。
                ossClient.shutdown();

                System.out.println(url);
                strings.add(url);
                ossClient.shutdown();

            }
        return AjaxResult.success(strings);
    }
}
